/**
 * 
 */
package os.filesystem.tool;

import java.util.ArrayList;
import java.util.List;

import os.filesystem.exception.FSMalformedCommandException;
import os.filesystem.file.Directory;
import os.filesystem.file.GeneralDirectory;
import os.filesystem.file.RootDirectory;
import os.filesystem.file.exception.FSFileException;

/**
 * Directories must always be created via this tool.
 * 
 * @author Raghav Sidhanti
 * @since Mar 6, 2012 10:38:32 AM
 * 
 */
public final class MkDir extends FSTool {

	public static final String COMMAND_NAME = "mkdir";

	public Directory mkdir(String name) {
		Directory workingDir = FSState.workingDir();

		Directory newDir = new GeneralDirectory(name, FSState.user);
		try {
			// Next three lines must be a transaction
			// TODO Make as transaction
			workingDir.add(newDir.getMeta());
			FSState.io.write(newDir);
			FSState.io.write(workingDir);
			return newDir;
		} catch (FSFileException e) {
			System.out.println(e.getMessage());
		}
		return null;
	}

	/**
	 * This method will blindly write the root directory to disks.
	 */
	public void mkrootdir() {
		RootDirectory rd = (RootDirectory) FSState.rootDir;
		FSState.io.write(rd);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see os.filesystem.tool.Tool#execute(java.util.List)
	 */
	@Override
	public void execute(Command command) throws FSMalformedCommandException {
		mkdir(command);
	}

	public List<Directory> mkdir(Command command) throws FSMalformedCommandException {
		List<Directory> directories = null;
		if (command.getNonOptionArguments().size() > 0 && command.getCommandNameArgument().getArgument().equals(COMMAND_NAME)) {
			Directory workingDir = FSState.workingDir();
			directories = new ArrayList<Directory>(command.getNonOptionArguments().size());
			for (Argument arg : command.getNonOptionArguments()) {
				if (!arg.isOption()) {
					Directory newDir = new GeneralDirectory(arg.getArgument(), FSState.user);
					// Next three lines must be a transaction
					// TODO Make as transaction
					try {
						workingDir.add(newDir.getMeta());
						FSState.io.write(newDir);
						FSState.io.write(workingDir);
						directories.add(newDir);
					} catch (FSFileException e) {
						System.out.println(e.getMessage());
					}
				}
			}
		} else {
			throw new FSMalformedCommandException("Wrong command. Please check manual for syntax.");
		}
		return directories;
	}
}
